<!-- 
 +----------------------------------------------------------------------
 | 狂团[kt8.cn]旗下KtAdmin是为独立版SAAS系统而生的快速开发框架.
 +----------------------------------------------------------------------
 | [KtAdmin] Copyright (c) 2022 http://ktadmin.cn All rights reserved.
 +----------------------------------------------------------------------
 | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
 +---------------------------------------------------------------------- 
-->
<script setup>
import { Download } from '@element-plus/icons-vue'
import { reactive, ref, onMounted, getCurrentInstance } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { cardRecordList } from '@/api'

const ruleFormLabelWidth = ref('80px')
const router = useRouter()
const dialogFormVisible = ref(false)
const ruleFormRef = ref()
const multipleSelection = ref([])
const formdata = reactive({
	page: 1,
	size: 10,
	nickname: ''
})
const isUnuse = ref(false)

const tempObj = ref({})
const handleSizeChange = (val) => {
	formdata.size = val
	getList()
}
const handleCurrentChange = (val) => {
	formdata.page = val
	getList()
}
const handleSizeChange1 = (val) => {
	query.size = val
	getTempData()
}
const handleCurrentChange1 = (val) => {
	query.page = val
	getTempData()
}
const save = async () => {
	const r = await postCardAdd(ruleForm)
	if (r) {
		dialogVisible.value = false
		getList()
	}
}
const dele = (id) => {
	ElMessageBox.confirm('确定要删除吗？', '提示', {
		type: 'warning',
		center: true
	}).then(() => {
		postCardDele({ id: id }).then((res) => {
			ElMessage({
				message: '删除成功',
				type: 'success'
			})
			getList()
		})
	})
}
const types = [
	// '对话次数','绘画次数','vip时长'
	'对话次数',
	'',
	'vip时长'
]
const sizes1 = ['条']
const sizes2 = ['日', '', '月', '', '年']
const tableData = [
	{
		id: 1,
		level: '1',
		name: '15538889999'
	}
]
const applist = ref([
	{
		img: 'http://weidogstest.oss-cn-beijing.aliyuncs.com/base/base_6319a895619a8.png',
		name: '主应用dmo'
	},
	{
		img: 'https://kt8logo.oss-cn-beijing.aliyuncs.com/app.png',
		name: '狂团demo插件'
	},
	{
		img: 'http://weidogstest.oss-cn-beijing.aliyuncs.com/svideo/1/svideo_62df5b8419da1.jpg',
		name: '企微魔盒'
	}
])
const handleSelectionChange = (val) => {
	multipleSelection.value = val
}
const appshow = ref(false)
const addapp = () => {
	appshow.value = true
}
// 获取数据,先定一个reactive ，不然赋值的数据不是响应式
let states = reactive({
	tableData: [
		{
			id: 1,
			name: 122
		}
	]
})

let isadmin = ref()
const getList = () => {
	cardRecordList(formdata).then((res) => {
		console.log(res, '3333')
		states.tableData = res.data.item
		states.total = res.data.count
		// isadmin.value = res.data.isadmin
	})
}

onMounted(() => {
	getList()
})
const dialogVisible = ref(false)
const addFun = () => {
	dialogVisible.value = true
	title.value = '生成卡密'
	Object.assign(ruleForm, {
		type: 1,
		size: 1,
		remark: '',
		amount: 1
	})
}
// const editFun = (val) => {
// 	ruleForm.name = val.name
// 	ruleForm.price = val.price
// 	ruleForm.id = val.id
// 	dialogVisible.value = true
// 	appidata.appindex = []
// 	ruleForm.specs = []
// 	ruleForm.name = ''
// 	packageinfo({ id: val.id }).then((res) => {
// 		ruleForm.name = res.data.name
// 		ruleForm.specs = res.data.specs
// 		appidata.appindex = res.data.apps
// 		console.log(appidata.appindex)
// 	})
// 	getMarketlist().then((res) => {
// 		applist.value = res.data
// 	})
// 	title.value = '编辑'
// }
const rules = reactive({
	name: [{ required: true, message: '请输入套餐名称', trigger: 'blur' }],
	price: [{ required: true, message: '请输入套餐价格', trigger: 'blur' }]
})
const deleteFun = (id) => {
	console.log(id)
	deleteTC(id).then((res) => {
		console.log(res)
		getList()
	})
}
const title = ref('新增')
const ruleForm = reactive({
	type: 1,
	size: 1,
	remark: '',
	amount: 1
})
const addlist = () => {
	var data = {
		id: ruleForm.specs.length > 0 ? ruleForm.specs[ruleForm.specs.length - 1].id + 1 : 1,
		duration: '',
		price: '',
		old_price: '',
		duration_type: '3'
	}
	console.log(ruleForm.specs, ruleForm.specs.length)
	ruleForm.specs.push(data)
}
// 删除表格一列
const deletelist = (val, row) => {
	if (ruleForm.specs.length == 1) {
		ElMessage({
			message: '无法删除，最少有一项',
			type: 'warning'
		})
	} else {
		ruleForm.specs.splice(val.index, 1)
	}
}
// 查询数据
const formInline = reactive({
	phoneNumber: '',
	region: '',
	state: ''
})
// 查询提交
const onSubmit = () => {
	console.log('submit!')
	console.log(formInline)
}
// 跳转

const testFun = (isadmin) => {
	console.log(isadmin)
}
const submitForm = async (formEl) => {
	if (title.value == '编辑') {
		if (!formEl) return
		await formEl.validate((valid, fields) => {
			if (valid) {
				console.log(appidata.appindex, ruleForm.specs, ruleForm.name)
				postCardAdd({ id: ruleForm.id, name: ruleForm.name, specs: ruleForm.specs, apps: appidata.appindex }).then(
					(res) => {
						ElMessage({ message: '提交成功', type: 'success' })
						dialogVisible.value = false
						getList()
					}
				)
				// updateddTC({ name: ruleForm.name, price: ruleForm.price, id: ruleForm.id }).then((res) => {
				// 	ElMessage({ message: '提交成功', type: 'success' })
				// 	dialogVisible.value = false
				// 	getList()
				// })
			} else {
				console.log('error submit!', fields)
				ElMessage({ message: '失败', type: 'info' })
			}
		})
	} else {
		if (!formEl) return
		await formEl.validate((valid, fields) => {
			if (valid) {
				postCardAdd({ name: ruleForm.name, specs: ruleForm.specs, apps: appidata.appindex }).then((res) => {
					ElMessage({ message: '提交成功', type: 'success' })
					dialogVisible.value = false
					getList()
				})
			} else {
				console.log('error submit!', fields)
				ElMessage({ message: '失败', type: 'info' })
			}
		})
	}
}
const appidata = reactive({
	appindex: [],
	appxuan: []
})
const isShowDetail = ref(false)
const query = reactive({
	id: '',
	page: 1,
	size: 20
})
const totalTemp = ref(0)
const tableDataTemp = ref([])
const editFun = async (id, row) => {
	// 查看弹窗

	tempObj.value = row

	query.id = id

	getTempData()
	isShowDetail.value = true

	// router.push({ path: 'add', query: { id: id } })
	// localStorage.setItem('temp',JSON.stringify(row))
}
const getTempData = async () => {
	const r = await postCardDetail(query)
	if (r) {
		totalTemp.value = r.data.count
		tableDataTemp.value = r.data.item
	}
}
const handleClose1 = () => {
	isShowDetail.value = false
}
const checkapp = (val, index) => {
	console.log(appidata.appindex, appidata.appxuan, appidata.appindex.indexOf(val.code))
	if (appidata.appindex.indexOf(val.code) != -1) {
		// appidata.appindex.splice(index, 1)
		// appidata.appxuan.splice(index, 1)
		for (var i = 0; i < appidata.appindex.length; i++) {
			if (val.code == appidata.appindex[i]) {
				appidata.appindex.splice(i, 1)
				appidata.appxuan.splice(i, 1)
				console.log(appidata.appindex)
			}
		}
	} else {
		appidata.appindex.push(val.code)
		appidata.appxuan.push(val)
		console.log(appidata.appindex)
	}
}
</script>

<template>
	<div class="public-container">
		<el-row>
			<el-col :span="24" style="margin-bottom: 10px">
				<div style="display: flex; justify-content: space-between">
					<!-- <el-button type="primary" @click="addFun">生成卡密</el-button> -->
					<!-- <el-input
						v-model="formdata.nickname"
						style="width: 200px"
						@change="
							formdata.page = 1
							getList()
						"
						placeholder="请输入昵称"
					></el-input> -->
				</div>
			</el-col>
		</el-row>
		<el-table
			ref="multipleTableRef"
			:data="states.tableData"
			style="width: 100%"
			:header-cell-style="{ color: '#909399', fontSize: '14px', backgroundColor: '#F7F9FA', padding: '10px 0' }"
			:cell-style="{ fontSize: '14px', padding: '20px 0' }"
			@selection-change="handleSelectionChange"
		>
			<el-table-column property="id" label="Id" width="80" />
			<el-table-column property="code" label="code码" />

			<el-table-column property="time" label="核销时间" />
			<el-table-column property="user" label="使用用户">
				<template #default="scope">
					<el-image
						style="width: 30px; height: 30px"
						v-if="scope.row.headimgurl"
						:src="scope.row.headimgurl"
					></el-image>
					{{ scope.row.un || '' }}
					<!-- {{ scope.row.mobile || '' }} [ID:{{ scope.row.user || '' }}] -->
				</template>
			</el-table-column>

	
			<el-table-column label="面额" width="170">
					<!-- <template #default="scope">
						<div>{{scope.row.month_num}}个月，每月{{ scope.row.month_max_duration }}分钟</div>
					</template> -->
					<template #default="scope">
						{{ scope.row.duration }}
						{{scope.row.duration_type==1?'天':scope.row.duration_type==2?'月':scope.row.duration_type==3?'年':''}}
						<!-- <div>{{scope.row.month_num}}个月，每月{{ scope.row.month_max_duration }}分钟</div> -->
					</template>
				</el-table-column>
			<!-- <el-table-column label="数量" width="150">
					<template #default="scope">
                        <div v-if="scope.row.size">
                          {{ scope.row.amount }}
                            {{ sizes[scope.row.size - 1] }}
                        </div>
                     
						
					</template>
				</el-table-column> -->

			<el-table-column property="remark" label="备注" />

			<!-- <el-table-column property="use_size" label="已使用" /> -->

			<!-- 	
				<el-table-column label="操作" width="150">
					<template #default="scope">
						<el-button link type="primary" @click="editFun(scope.row.id,scope.row)"> 查看 </el-button>
						<el-button link type="primary" @click="dele(scope.row.id)">删除 </el-button>
					
					</template>
				</el-table-column> -->
		</el-table>
		<div style="margin-top: 7px; float: right">
			<el-pagination
				v-model:currentPage="formdata.page"
				v-model:page-size="formdata.size"
				:page-sizes="[10, 20, 30, 40]"
				:small="small"
				:disabled="disabled"
				:background="background"
				layout="total, sizes, prev, pager, next, jumper"
				:total="states.total"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
			/>
		</div>
	</div>
	<!-- 弹窗 -->
	<el-dialog v-model="dialogVisible" :title="title">
		<el-form :model="ruleForm">
			<el-form-item label="类型" :label-width="ruleFormLabelWidth">
				<el-radio-group style="margin-left: -20px" v-model="ruleForm.type" placeholder="请选择">
					<span v-for="(item, index) in types">
						<el-radio style="margin-left: 20px" v-if="item != ''" :label="index + 1">
							{{ item }}
						</el-radio>
					</span>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="卡密数量" :label-width="ruleFormLabelWidth">
				<el-input style="width: 200px" v-model="ruleForm.amount" autocomplete="off" />
			</el-form-item>

			<el-form-item
				:label="ruleForm.type == 1 ? sizes1[ruleForm.size - 1] + '数' : '时长'"
				:label-width="ruleFormLabelWidth"
			>
				<el-input style="width: 200px" v-model="ruleForm.size_num" autocomplete="off">
					<template #append v-if="ruleForm.type != 1">{{ sizes2[ruleForm.size - 1] }}</template>
				</el-input>
			</el-form-item>

			<el-form-item label="单位" :label-width="ruleFormLabelWidth">
				<el-select v-if="ruleForm.type == 1" v-model="ruleForm.size" placeholder="请选择">
					<el-option v-for="(item, index) in sizes1" v-if="item" :label="item" :value="index + 1" />
				</el-select>
				<el-select v-else v-model="ruleForm.size" placeholder="请选择">
					<el-option v-for="(item, index) in sizes2" v-if="item" :label="item" :value="index + 1" />
				</el-select>
			</el-form-item>
			<el-form-item label="备注" :label-width="ruleFormLabelWidth">
				<el-input type="textarea" v-model="ruleForm.remark" autocomplete="off" />
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="save">保存</el-button>
			</span>
		</template>
	</el-dialog>

	<!-- 详情 -->

</template>

<style lang="scss" scoped>
.public-container {
	margin: 20px 0px 0 0px !important;
	background: #fff;
	// padding: 20px;
	border-radius: 4px;
}
.card-drawer {
	.ml20 {
		margin-left: 20px;
	}
}
</style>
